<script lang="ts" setup>
import type { RendererElement } from 'vue';

const props = defineProps<{
  contentClass?: string;
}>();
const expanded = defineModel<boolean>('expanded', { default: false });

function toggle() {
  expanded.value = !expanded.value;
}

function enter(el: RendererElement) {
  el.style.height = '0';
  void el.offsetHeight; // 触发回流，确保过渡效果生效
  el.style.height = `${el.scrollHeight}px`;
}

function leave(el: RendererElement) {
  el.style.height = `${el.scrollHeight}px`;
  void el.offsetHeight; // 触发回流，确保过渡效果生效
  el.style.height = '0';
}

function afterEnter(el: RendererElement) {
  el.style.height = 'auto';
}

function afterLeave(el: RendererElement) {
  el.style.height = null;
}
</script>

<template>
  <div>
    <slot name="trigger" :toggle="toggle" :expanded="expanded" />

    <Transition @enter="enter" @leave="leave" @afterEnter="afterEnter" @afterLeave="afterLeave">
      <div v-show="expanded" class="expand-content" :class="[props.contentClass]">
        <slot />
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.expand-content {
  overflow: hidden;
  transition: height 150ms ease-out;
}
</style>
